package com.example.videoview

import android.media.PlaybackParams
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    //保存视频进度的变量
    private var savePostion = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //本地视频的存放路径
        //val videoPath = "android.resource://$packageName/${R.raw.video1}"
        //videoView.setVideoPath(videoPath)
        //播放网络视频
        videoView.setVideoPath("https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209105011F0zPoYzHry.mp4")

        //视频播放器的控制条
        //videoView.setMediaController(MediaController(this))
        //视频播放前的监听
        videoView.setOnPreparedListener {
            //Log.d("hello", "onCreate:$it")
           //视频缓存前的进度
            progressBar2.visibility = View.INVISIBLE
            //设置进度条的最大时间
            progressBar.max = it.duration
            //自动循环播放
            it.isLooping = true
            //从3s处开始播放
            //it.seekTo(3000)
            //播放属性设置
            it.playbackParams = PlaybackParams().apply {
                //播放速度2倍
                //speed = 2f
                //音高
                //pitch = 2f
            }
            //从上次的进度开始播放视频(本地视频能实现按照上次播放的进度播放，但播放的不平滑）
            //播放网络视频不能实现
            it.seekTo(savePostion)
            //自动播放
            it.start()
        }
        //开始播放
        //videoView.start()
        //每隔半秒更新进度条
        //lifecycleScope.launch需要添加依赖
        // implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-rc03'
        lifecycleScope.launch {
            while(true){
                //如果视频在播放，就刷新进度条
                if(videoView.isPlaying){
                    progressBar.progress = videoView.currentPosition
                }
               //延迟半秒后再次刷新
                delay(500)
            }
        }

    }

    //视频切换时
    override fun onPause() {
        super.onPause()
        //获得当前视频的进度
        savePostion = videoView.currentPosition
    }
}